// by Jens Schmidt 2009
// for: YOU
// use, modify, copy this as you like

var UploadQueue = Class.create ({
	initialize: function(callback){
		this.list=new Array;
		this.db = new Mojo.Depot({
			name: "ext:uploadQueue",
			version: 1,
			estimatedSize: 10000,
			replace: false
		}, this.loadDbOpenOk.bind(this), this.dbFail.bind(this)
		);
	this.dbState='started';
	this.callback=callback;
	},
	
	dbFail: function() {
		this.dbState='fail';
		if (this.callback){
			this.callback(this.dbState);
		}
	},
	
	loadDbOpenOk: function() {
		this.dbState='open';
        this.db.get("uploadQueue", this.loadDbGetSuccess.bind(this), this.dbFail.bind(this));
    },
	
	reload: function(){
		if (this.dbState!='started' && this.dbState!='open'){
			this.db.get("uploadQueue", this.loadDbGetSuccess.bind(this), this.dbFail.bind(this));
		}
	},
	loadDbGetSuccess: function(queue) {
        if (queue === null || Object.toJSON(queue) == "{}") {
			// no worries, empty list
			this.dbState='fail';
        } else {
            this.list = queue;
			this.dbState='loaded length='+this.list.length;
        }
		if (this.callback){
			this.callback(this.dbState);
		}
    },
	stored: function(){
		if(this.callback)
		{
			this.callback('updated')
		}
	},
	
	storeDb: function() {
		if (this.list) {
			this.db.add("uploadQueue", this.list,this.stored.bind(this), this.dbFail.bind(this));
			return({'state':'stored='+this.list.length+' state='+this.dbState});
		}else{
			return({'err':'noStore'});
		}
    },
	
	storeElement: function(index,data){
		if (this.list) {
			if (index<0 || index>this.list.length) {
				this.list.push({
					filename: data.filename,
					caption: data.caption,
					description: data.description,
					privacy: data.privacy,
					shownName: data.shownName
				});
			}
			else {
				this.list[index] = {
					filename: data.filename,
					caption: data.caption,
					description: data.description,
					privacy: data.privacy,
					shownName: data.shownName
				};
			}
		}else{
			this.list=[
					{filename: data.filename,
					caption: data.caption,
					description: data.description,
					privacy: data.privacy,
					shownName: data.shownName}]
		}
		return (this.storeDb());
	},
	
	deleteElement: function(index){
		if (this.list && index >= 0 && index < this.list.length) {
			this.list.splice(index, 1);
		}
		return(this.storeDb());
	},
	
	findElement: function(filename){
		if (this.list) {
			for (var i = 0; i < this.list.length; i++) {
				if (this.list[i] && (this.list[i].filename === filename)) {
					return (i);
				}
			}
		}
		return(-1);
	}
})